﻿using System;
using System.IO;
using Mnk.Merger.Code.Repository;
using Mnk.Merger.Code.Settings;

namespace Mnk.Merger.Code.Commands
{
    class MergePathsBuilder : IMergePathsBuilder
    {
        private readonly MergeConfig mergeConfig;
        private readonly IRepositoryFacade facade;

        public MergePathsBuilder(MergeConfig mergeConfig, IRepositoryFacade facade)
        {
            this.mergeConfig = mergeConfig;
            this.facade = facade;
        }

        public bool BuildParams(string projectName, out string workingDirectory, out string mergeUrl, out string revisions)
        {
            workingDirectory = FixRoot(mergeConfig.SourcesFolder) + projectName;
            Console.WriteLine("Directory to merge to: " + workingDirectory);
            mergeUrl = FixRoot(mergeConfig.MergeUrl) + projectName;
            Console.WriteLine("Repository to merge from: " + mergeUrl);
            Console.WriteLine("Current branch: " + facade.GetInfo(workingDirectory).Url);
            revisions = facade.GetLatestMergedRevisions(workingDirectory, mergeUrl);
            var toMerge = facade.GetRevisionToMerge(workingDirectory, mergeUrl);

            Console.WriteLine("Not committed revisions: '{0}', next to merge: '{1}', total progress: {2}/{3}", revisions, toMerge.RevisionsToMerge, toMerge.Merged, toMerge.Total);
            Console.WriteLine("Validation: '{0}'", string.Join(Environment.NewLine, mergeConfig.Validation));
            if (!Directory.Exists(workingDirectory))
            {
                Console.WriteLine("Directory not exits: " + workingDirectory);
                return false;
            }
            return true;
        }

        private static string FixRoot(string source)
        {
            source = source.Trim().Replace("\\", "/");
            if (!source.EndsWith("/")) source += "/";
            return source;
        }
    }
}